<?php

namespace Lib;

class System {

    static $instance = false;
    static $cacheFile = true;

    static function getInstance() {
        if (!self::$instance)
            self::$instance = new System;
        return self::$instance;
    }

    public function init($cacheFile = 0) {
        session_start();
        self::$cacheFile = $cacheFile;
        if (System::$cacheFile)
            include SITE_PATH . 'tmp/classes.php';
        spl_autoload_register(function ($class) {
                    $class = str_replace('\\', '/', $class);
                    $file = SITE_PATH . $class . '.class.php';
                    if (file_exists($file)) {
                        require_once $file;
                        if (System::$cacheFile) {
                            $fp = fopen(SITE_PATH . 'tmp/classes.php', 'a');
                            $str = file_get_contents($file);
                            $str = preg_replace("/\?>[\w\W]+&/i", "", $str);
                            $str = preg_replace("/\^[\w\W]+<\?/i", "", $str);
                            fputs($fp, $str);
                            fclose($fp);
                        }
                    }
                });

        $config = \Lib\Config::getInstance();
        Registry::set('config', $config);    
                
        $trans = \Lib\Trans::getInstance();
        Registry::set('trans', $trans);
                
        $db = \Lib\Database::getConnection();
        Registry::set('db', $db);

        $cache = new \Lib\Cache('tmp/cache');
        Registry::set('cache', $cache);

        $view = new \Lib\View('template');
        Registry::set('view', $view);

        $router = \Lib\Router::getInstance();
        $router->setPath('Module');
        Registry::set('router', $router);
        $router->delegate();

        return $this;
    }

}

?>
